import ma.fs.dfs.dfsflags as dfsflags
import ma.const

input_filename = ma.const.XmlData.get_str_data(ma.const.xml_map_flags_filename)
new_mapflags_filename = 'mapflags_out.xml'
struct_id_order = [ '68', '62', '44', '29', '64', '3', '54', '11', '18', '22', '25', '61', '26', '66', '47', '32', '38', '28', '60', '21', '69', '30', '9', '72', '4', '37', '53', '34', '70', '8', '55', '5', '0', '39', '36', '24', '48', '19', '16', '59', '14', '12', '71', '41', '50', '67', '2', '1', '17', '13', '10', '7', '6', '15', '20', '31', '27', '23', '35', '40', '33', '46', '43', '49', '42', '58', '45', '51', '52', '57', '63', '56', '65' ]
#struct_id_order = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72' ]

xml_str = dfsflags.DfsFlags._DfsFlags__mapflag_template
mfs = ""

mapflag_start = "<mt>"
mapflag_end = "</mt>"
append_idx_end = len(mapflag_end)

# read the input file
mf_fd = open(input_filename, 'r')
mf_str = mf_fd.read()
mf_fd.close()

# iterate through all structs
for struct_id in struct_id_order:
    search_idx = 0
    struct_str = '<strc>' + str(struct_id) + '</strc>'
    
    search_idx = mf_str.find(struct_str, search_idx)
    while search_idx != -1:
        # get the starting and ending indexes
        start_idx = mf_str.rfind(mapflag_start, 0, search_idx)
        end_idx = mf_str.find(mapflag_end, search_idx) + append_idx_end
        
        # get the current map's str and add to the main str
        current_map_str = mf_str[start_idx:end_idx]
        mfs += current_map_str
        
        search_idx = mf_str.find(struct_str, search_idx+1)
    
xml_str = xml_str % mfs

mf_fd = open(new_mapflags_filename, 'w+')
mf_fd.write(xml_str)
mf_fd.close()
